const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');

let localStream;
let peerConnection;
let remoteDescriptionSet = false; // 新增标志
let socket;

const servers = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' }
    ]
};

function start() {
    navigator.mediaDevices.getUserMedia({ video: true, audio: true })
        .then(stream => {
            localStream = stream;
            localVideo.srcObject = stream;

            createPeerConnection();

            startButton.disabled = true;
            stopButton.disabled = false;
        })
        .catch(error => {
            console.error('Error accessing media devices.', error);
        });
}

function stop() {
    if (localStream) {
        localStream.getTracks().forEach(track => track.stop());
    }

    if (peerConnection) {
        peerConnection.close();
        peerConnection = null;
    }

    if (socket) {
        socket.close();
        socket = null;
    }

    localVideo.srcObject = null;
    remoteVideo.srcObject = null;

    startButton.disabled = false;
    stopButton.disabled = true;
}

function createPeerConnection() {
    peerConnection = new RTCPeerConnection(servers);

    peerConnection.addStream(localStream);

    peerConnection.onicecandidate = handleIceCandidate;
    peerConnection.ontrack = handleRemoteTrack;

    createOffer();
}

function createOffer() {
    peerConnection.createOffer()
        .then(offer => peerConnection.setLocalDescription(offer))
        .then(() => sendSignalingMessage(peerConnection.localDescription))
        .catch(error => console.error('Error creating offer:', error));
}

function handleIceCandidate(event) {
    if (event.candidate) {
        sendSignalingMessage({ type: 'candidate', candidate: event.candidate });
    }
}

function handleRemoteTrack(event) {
    remoteVideo.srcObject = event.streams[0];
}

function sendSignalingMessage(message) {
    if (!socket) {
        socket = new WebSocket('wss://192.168.2.20:8080/websocket');
        socket.onopen = () => socket.send(JSON.stringify(message));
        socket.onmessage = event => {
            const data = JSON.parse(event.data);
            if (data.type === 'answer') {
                peerConnection.setRemoteDescription(new RTCSessionDescription(data))
                    .then(() => {
                        remoteDescriptionSet = true; // 设置标志
                        // 重新处理之前未处理的ICE候选
                        processPendingCandidates();
                    })
                    .catch(error => console.error('Error setting remote description:', error));
            } else if (data.type === 'candidate') {
                if (remoteDescriptionSet) {
                    peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                        .catch(error => console.error('Error adding ICE candidate:', error));
                } else {
                    // 如果远程描述尚未设置，暂存ICE候选
                    pendingCandidates.push(data.candidate);
                }
            } else if (data.type === 'offer') {
                peerConnection.setRemoteDescription(new RTCSessionDescription(data))
                    .then(() => createAnswer())
                    .catch(error => console.error('Error setting remote description:', error));
            }
        };
    } else {
        socket.send(JSON.stringify(message));
    }
}

let pendingCandidates = []; // 暂存未处理的ICE候选

function processPendingCandidates() {
    for (const candidate of pendingCandidates) {
        peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
            .catch(error => console.error('Error adding ICE candidate:', error));
    }
    pendingCandidates = []; // 清空暂存列表
}

function createAnswer() {
    peerConnection.createAnswer()
        .then(answer => peerConnection.setLocalDescription(answer))
        .then(() => sendSignalingMessage(peerConnection.localDescription))
        .catch(error => console.error('Error creating answer:', error));
}

startButton.addEventListener('click', start);
stopButton.addEventListener('click', stop);